<!DOCTYPE HTML>
<html>
<head>
    {include file="common:meta"}
    <link type="text/css" rel="stylesheet" href="/static/admin/plugin/bootstrap-fileinput/css/fileinput.css"/>
</head>
<body>
<div class="page-container">
    <div class=" float-e-margins">
        <div class="ibox-content">
            <div class="tabs-container">
                <ul class="nav nav-tabs">
                    <li class="active"><a data-toggle="tab" href="#tab-1" aria-expanded="true">兑换列表</a>
                    </li>
                    <li class=""><a data-toggle="tab" href="#tab-2" aria-expanded="true">兑换添加</a>
                    </li>
                </ul>
                <div class="tab-content">
                    <div class=" tab-pane active" id="tab-1">
                        <form action="" class="form-inline" data-url="">
                            <div class="form-group">
                                <label class="control-label" for="key">选项:</label>
                                <select id="key" class="form-control" name="key">
                                    <!--<option value="u_id">ID</option>-->
                                    <!--<option value="account">赠送类型</option>-->
                                    <!--<option value="admin">管理员</option>-->
                                </select>
                            </div>
                            <div class="form-group">
                                <label class="control-label" for="value">输入:</label>
                                <input class="form-control" id="value" type="text" name="value">
                            </div>
                            <button type="button" class="btn btn-primary" id="eventQuery">查询</button>
                            <button type="button" onclick="location.replace(location.href);" class="btn btn-success ">刷新</button>
                        </form>
                        <table id="tb_departments"></table>
                    </div>
                    <div class="tab-pane" id="tab-2">
                        <div class="ibox-content">
                            <form class="form-horizontal"  id="form"   data-url="/PropExchangeAdd" enctype="multipart/form-data">

                                <div class="form-group">
                                    <label class="col-sm-2 control-label" for="type">
                                        <span class="c-red">*</span>兑换类型：
                                    </label>
                                    <div class="col-md-2 col-sm-10">
                                        <select class="form-control" name="type" id="type">
                                            <option value="1">钻石</option>
                                            <option value="1">待定</option>
                                            <option value="1">待定</option>
                                            <option value="1">待定</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-2 control-label" for="state">
                                        <span  class="c-red">*钻石个数：</span>
                                    </label>
                                    <!--<div class="col-md-2 col-sm-10">-->
                                        <!--<select class="form-control " name="gift_id" id="gift_id"></select>-->
                                    <!--</div> -->
                                    <div class="col-md-2 col-sm-10">
                                        <input class="form-control" min="1" type="number" name="state" id="state">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-2 control-label" for=>
                                        <span class="c-red">*</span>领取条件：
                                    </label>
                                    <div class="col-md-1 col-sm-5">
                                        <select class="form-control price_id" name="prop_id[]" ></select>
                                    </div>
                                    <div class="col-md-1 col-sm-5">
                                        <input type="number" class="form-control price_id" min="1" placeholder="所需数量" name="prop_num[]" >
                                    </div>
                                    <button type="button" class="add btn btn-primary btn-sm" style="margin-right:15px;">+</button>
                                </div>


                                <div class="form-group">
                                    <label class="col-sm-2 control-label">
                                        <span class="c-red">*</span>状态：
                                    </label>
                                    <div class="col-md-2 col-sm-10">
                                        <div class="radio i-checks">
                                            <label><input type="radio"  name="status" value="2"> <i></i>禁止兑换</label>
                                            <label><input type="radio" name="status"  value="1" checked> <i></i>开启兑换</label>
                                        </div>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-2 control-label" for="exchange_pic">
                                        <span class="c-red">*</span>兑换图片：
                                    </label>
                                    <div class="col-md-4 col-sm-10">
                                        <input id="exchange_pic"  class="form-control" type="file" name="exchange_pic">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-2 control-label" for="bg_pic">
                                        <span class="c-red">*</span>背景图：
                                    </label>
                                    <div class="col-md-4 col-sm-10">
                                        <input id="bg_pic"  class="form-control" type="file" name="bg_pic">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-2">
                                        <button class="btn btn-primary" type="button" onclick="commonSubmit(this)">添加
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{include file="common:footer"}
<script type="text/javascript" src="/static/admin/plugin/bootstrap-fileinput/js/fileinput.js"></script>
<script type="text/javascript" src="/static/admin/plugin/bootstrap-fileinput/js/locales/zh.js"></script>
<script>

    $(document).ready(function () {
        initTable();
        getProp();
        displayAll($("#exchange_pic"));
        displayAll($("#bg_pic"));
    });
    function displayAll(obj) {
        obj.fileinput({
            language: 'zh', //设置语言

            uploadUrl: "/PropExchangeAdd", //上传的地址

            allowedFileExtensions: ['apk', 'jpg', 'png', 'jpeg','webp'],//接收的文件后缀

            uploadAsync: false, //默认异步上传

            showUpload: false, //是否显示上传按钮

            showRemove: true, //显示移除按钮

            showPreview: true, //是否显示预览

            browseClass: "btn btn-primary", //按钮样式

            maxFileCount: 1, //表示允许同时上传的最大文件个数

            enctype: 'multipart/form-data',

            validateInitialCount: true,

            previewFileIcon: "<iclass =" + 'glyphicon glyphicon-king' + "></i>",

            msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"
        }).on("filebatchuploadsuccess", function (event, data) {
            if (data) {
                $("#img_address").val(data.response);
            }
        });
    }
    function initTable() {
        $('#tb_departments').bootstrapTable({
            url: '/PropExchangeIndexData',         //请求后台的URL（*）
            dataField: "data",
            method: 'get',                      //请求方式（*）
            striped: true,                      //是否显示行间隔色
            cache: true,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            queryParams: queryParams,//传递参数（*）
            showToggle: true,
            showRefresh: true,
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            showColumns: true,                  //是否显示所有的列
            showPaginationSwitch: true,
            minimumCountColumns: 2,             //最少允许的列数

            columns: [{
                field: 'prop_ids',
                title: '兑换条件',
                align: 'center'
            }, {
                field: 'state',
                title: '兑换奖品',
                align: 'center'
            },{
                field: 'type',
                title: '类型',
                formatter: function (value, row, index) {
                    var arr = []; arr[1] = '钻石'; arr[2] = '金币';
                    return arr[row.type];
                },
                align: 'center'
            }, {
                field: 'status',
                title: '状态',
                formatter: function (value, row, index) {
                    var arr = []; arr[1] = '已开启'; arr[2] = '已关闭';
                    return arr[row.status];
                },
                align: 'center'
            }, {
                field: 'Button',
                title: '操作',
                events: operateEvents,
                formatter: operateFormatter
            }]
        });
    }

    //得到查询的参数
    function queryParams(params) {
        params.offset = params.offset / params.limit + 1;
        params.key = $('#key').val();
        params.value = $('#value').val();
        console.log(JSON.stringify(params));
        return params;
    }

    function operateFormatter(value, row, index) {
        var status = row.status === 1 ? '关闭兑换' : '开启兑换';
        var button_status = row.status === 1 ? 'btn-danger' : 'btn-primary';
        return [
            '<button type="button"  class="TableChange btn '+button_status +' btn-sm" style="margin-right:15px;">' + status + '</button>'
        ].join('');
    }

    window.operateEvents = {
        'click .TableChange': function (e, value, row, index) {
            changeStatus('PropExchangeChangeStatus', row, this);
        }
    };

    function changeStatus(url, row, obj) {
        $.ajax({
            type: 'get',
            dataType: 'json',
            url: url,
            data: {'id': row.id},
            success: function (re) {
                if (re.code === 100) {
                    layer.msg(re.msg, {icon: 1, time: 2000});
                    $('#tb_departments').bootstrapTable(('refresh'));	// 很重要的一步，刷新url！
                } else {
                    layer.alert(re.msg);
                }
            },
            error: function (data) {
                console.log(data.msg);
            }
        });
    }
    function getProp(){
        $.ajax({
            type: 'get',
            dataType: 'json',
            url: '/PropIndexData',
//            data: {'prize_type': 4},
            success: function (re) {
//                if (re.code === 100) {

                    console.log(re);
                    var htmlText = "<option value='' selected>--请选择--</option>";
                    if(re.data !== null){

                        for(var i in re.data){

                            htmlText+="<option value="+ re.data[i]['id']+">"+ re.data[i]['prop_name']+"</option>";
                        }
                        $('.price_id').html(htmlText);
//                        $('#gift_id').html(htmlText);
                    }
//                }else{
//                    layer.msg(re.msg,{
//                        icon:2,
//                        time:1500
//                    });
//                }
            }
        });
    }
    $('.add').click(function(){


        var parent = $(this).parent();
        console.log(parent[0]);
        var htmlText = parent[0];
        htmlText = ' <div class="form-group">'+
            '<label class="col-sm-2 control-label"><span class="c-red">*</span>领取条件:</label>'+
             '<div class="col-md-1 col-sm-5">'+
            '<select class="form-control price_id" name="prop_id[]" ></select></div>'+
           '<div class="col-md-1 col-sm-5">'+
            '<input type="number" class="form-control price_id" placeholder="所需数量" min="1" name="prop_num[]" ></div>';
//           '<button type="button" class="add btn btn-primary btn-sm" style="margin-right:15px;">+</button></div>';
        $(this).parent().after(htmlText);
        getProp();
    });


    // 索按钮触发事件
    $(function () {
        $("#eventQuery").click(function () {
            $('#tb_departments').bootstrapTable(('refresh'));	// 很重要的一步，刷新url！
        });
    });


    /**
     * 提交表单
     * @returns {boolean}
     */
    function commonSubmit(obj) {

        var form = $("#form");
        var formData = new FormData(form[0]);
        console.log(formData);
        $(obj).attr('disabled', true).addClass('disabled');
        var url_ = form.attr('data-url');
        $.ajax({
            url: url_,
            type: 'POST',
            dataType: 'json',
            // data: form.serialize(),
            data:formData,
            processData: false,
            contentType: false,
            cache: false,
            async: false,
            success: function (re) {
                // console.log(re);
                $(obj).removeAttr('disabled', true).removeClass('disabled');
                if (re.code === 100) {
                    layer.msg(re.msg, {
                        icon: 1,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒
                    }, function () {
                        re.url ? window.location.href = re.url : '';
                    });
                } else {
                    layer.msg(re.msg,{ icon: 2,time: 2000});
                }
            }
        });
        return false;
    }
</script>
</body>
</html>